package util;

import repository.DatabaseConnector;

import java.sql.*;

public class checkDuplicateEntry {
    public static boolean checkDuplicateEntry(double amount, Timestamp datetime) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 获取数据库连接
            connection = DatabaseConnector.getConnection();
            assert connection != null;

            // 准备查询语句，检查amount和datetime是否重复
            String query = "SELECT COUNT(*) FROM balances WHERE amount = ? AND datetime = ?";
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setDouble(1, amount);
            preparedStatement.setTimestamp(2, datetime);

            // 执行查询
            resultSet = preparedStatement.executeQuery();

            // 检查是否有重复的记录
            if (resultSet.next()) {
                int count = resultSet.getInt(1);
                return count > 0; // 如果count大于0，则存在重复记录
            }

            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 关闭资源
            DatabaseConnector.closeResultSet(resultSet);
            DatabaseConnector.closePreparedStatement(preparedStatement);
            DatabaseConnector.closeConnection(connection);
        }
    }
}

